#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
@author zyx
@since 2022/2/27 18:21
@file: c03_mongo_wrap.py
@desc: mongo封装方法案例
"""
from pymongo import MongoClient


# 创建返回链接对象
def get_db(database):
    client = MongoClient(host="localhost", port=27017)
    db = client[database]
    return client, db


# ==================== 增删改查 ====================
# 增加数据
def add_one(table, data):
    client, db = get_db("python")
    result = db[table].insert_one(data)
    client.close()
    return result


def add_many(table, data_list):
    client, db = get_db("python")
    result = db[table].insert_many(data_list)
    client.close()
    return result.inserted_ids


# 更新数据
def upd(table, condition, data):  # condition条件
    client, db = get_db("python")
    result = db[table].update_many(condition, {'$set': data})
    client.close()
    return result


# 删除数据
def delete(table, condition):  # condition条件
    client, db = get_db("python")
    result = db[table].delete_many(condition)
    client.close()
    return result


if __name__ == '__main__':
    # r = add_one("stu", {"name": "西瓜", "age": 18, "hobbies": ["喝酒", "抽烟", "烫头"]})
    # print(r.inserted_id)

    # r = add_many("stu", [{"name": "嘎嘎"},{"name": "咔咔"}])
    # print(r)

    result = upd("stu", {"name": '西瓜'}, {"age": 100})
    print(result)

    # result = delete("stu", {"name": "嘎嘎"})
    # print(result)

    pass
